package com.aididi.producer;

import com.aididi.entity.Order;
import com.aididi.mapper.BrokerMessageLogMapper;
import com.aididi.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Auther: zx.xu
 * @Description:
 */
@Component
@Slf4j
public class SendMessage {

    private final RabbitTemplate rabbitTemplate;

    private BrokerMessageLogMapper brokerMessageLogMapper;

    @Autowired
    public SendMessage(RabbitTemplate rabbitTemplate,BrokerMessageLogMapper brokerMessageLogMapper) {
        this.rabbitTemplate = rabbitTemplate;
        this.brokerMessageLogMapper = brokerMessageLogMapper;
    }

    /**
     * 回调函数：confirm确认
     */
    private final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         *
         * @param correlationData   消息唯一id
         * @param ack   是否成功
         * @param s
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String s) {
            log.info("correlationData: {}",correlationData);
            String messageId = correlationData.getId();
            if(ack){
                //如果confirm返回成功则进行更新
                brokerMessageLogMapper.changeBrokerMessageLogStatus(messageId, Constants.ORDER_SEND_SUCCESS,new Date());
            }else{
                //失败进行重试或补偿
                log.info("异常处理...");
            }
        }
    };



    /**
     * 发送消息方法调用：构建自定义对象消息
     * @param order
     */
    public void sender(Order order){
        rabbitTemplate.setConfirmCallback(confirmCallback);
        CorrelationData correlationData = new CorrelationData(order.getMessageId());
        rabbitTemplate.convertAndSend("order-exchange","order.key1",order,correlationData);
    }
}
